package com.pig4cloud.pig.ads.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pig4cloud.pig.ads.pig.mapper.AdvertiserMapper;
import com.pig4cloud.pig.ads.service.SelectListService;
import com.pig4cloud.pig.ads.service.TtAccesstokenService;
import com.pig4cloud.pig.ads.utils.OEHttpUtils;
import com.pig4cloud.pig.api.entity.ResponseBean;
import com.pig4cloud.pig.common.core.util.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

@Service
public class SelectListServiceImpl implements SelectListService {

	@Autowired
    TtAccesstokenService ttAccesstokenService;

	@Autowired
	private AdvertiserMapper advertiserMapper;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;



	@Override
	public R czSite(String advertiserId, Integer page, Integer pageSize) {
		Map<String, Object> reqData = new HashMap<String, Object>();
		reqData.put("advertiser_id", advertiserId);
		// status 已上线（包括建站状态中：enable，auditAccepted，auditDoing）
		reqData.put("status","SITE_ONLINE");
		if (page!=null) {
			reqData.put("page", page);
		}
		if (pageSize != null) {
			reqData.put("page_size", pageSize);
		}else {
			reqData.put("page_size", 300);
		}



		Map<String, Object> data = new HashMap<>();
		String token = ttAccesstokenService.fetchAccesstoken(advertiserId);

		try {
			JSONArray list = iterationGet(reqData, token);
			for (int i=0; i<list.size(); i++){
				JSONObject item = list.getJSONObject(i);
				item.put("jz_url","https://www.chengzijianzhan.com/tetris/page/" + item.getString("siteId") );
			}
			data.put("list", list);
			return R.ok(data, "获取成功");
		} catch (Exception e) {
			return R.failed("从toutiao获取失败:" + e.getMessage());
		}
	}

	public JSONArray iterationGet(Map<String, Object> reqData, String token) throws Exception {
		ResponseBean resBean = new ResponseBean();
		JSONArray adList = new JSONArray();
		Integer page = 1;
		while (true) {
			try {
				reqData.put("page", String.valueOf(page));
				//获取广点通公共报文头
				String resultStr = OEHttpUtils.doGet("https://ad.oceanengine.com/open_api/2/tools/site/get/", reqData, token);
				resBean = JSON.parseObject(resultStr, ResponseBean.class);
				//调用成功,信息入库
				if(resBean != null && "0".equals(resBean.getCode())){
					JSONObject jsonObj = resBean.getData();
					JSONArray list = jsonObj.getJSONArray("list");
					adList.addAll(list);


					String pageinfoStr = jsonObj.getString("page_info");//分页配置信息
					JSONObject pageinfo = JSONObject.parseObject(pageinfoStr);
					page = pageinfo.getInteger("page");
					Integer total_page = pageinfo.getInteger("total_page");//总页数
					if (new BigInteger(String.valueOf(page)).compareTo(new BigInteger(String.valueOf(total_page))) >= 0) {
						break;
					}
					page++;
				} else {
					throw new Exception(resBean == null ? "" : resBean.getMessage());
				}
			} catch (Throwable e) {
				throw new Exception("获取自定义落地页异常,"+e.getMessage());
			}
		}
		return adList;
	}


	@Override
	public R actionTextList(String advertiserId, String landingType) {
		Map<String, Object> reqData = new HashMap<String, Object>();
		reqData.put("advertiser_id", advertiserId);

		if (StringUtils.isNotEmpty(landingType))
			reqData.put("landing_type", landingType);
		else
			reqData.put("landing_type", "APP");


		String token = ttAccesstokenService.fetchAccesstoken(advertiserId);		// this.getAccesstoken(advertiserId);
		//token = "b94ebce6e83cecb6fd9430893a949763163b1974";

		//调用头条接口
		String resultStr = OEHttpUtils.doGet("https://ad.oceanengine.com/open_api/2/tools/action_text/get/", reqData, token);

		//结果为null，当做失败
		if (StringUtils.isBlank(resultStr))
			return R.failed("从toutiao获取失败:resultStr is blank");

		JSONObject obj = JSON.parseObject(resultStr);
		if (!obj.getInteger("code").equals(0)){	//同步失败
			return R.failed("从toutiao获取失败:" + obj.getString("message"));
		}else{
			JSONArray data = obj.getJSONArray("data");
			return R.ok(data, "获取成功");
		}
	}

	@Override
	public R callToActionList(String advertiserId, String recommendType, String advancedCreativeType) {
		//
		String[] data = {"立即下载", "免费下载", "开启探险", "抢先挑战", "玩家福利", "官方下载", "新手礼包", "立即闯关", "领取角色", "极速下载", "等你来战", "安全下载", "点我玩玩"};
/*
		Map<String, Object> reqData = new HashMap<String, Object>();
		reqData.put("advertiser_id", advertiserId);

		if (StringUtil.isNotEmpty(recommendType))
			reqData.put("recommend_type", recommendType);
		else
			reqData.put("recommend_type", "CALL_TO_ACTION");

		if (StringUtils.isNotBlank(advancedCreativeType))
			reqData.put("advanced_creative_type", advancedCreativeType);
		else
			reqData.put("advanced_creative_type", "ATTACHED_CREATIVE_NONE");


		String token = ttAccesstokenService.fetchAccesstoken(advertiserId);		// this.getAccesstoken(advertiserId);
		//String accessToken = "3e09cc34a5812083ad9bd2f9eca6659fe2aadaa6";

		//调用头条接口
		String resultStr = OEHttpUtils.doGet("https://ad.oceanengine.com/open_api/2/tools/promotion_card/recommend/get/", reqData, token);

		//结果为null，当做失败
		if (StringUtils.isBlank(resultStr))
			return R.failed("从toutiao获取失败 ");

		JSONObject obj = JSON.parseObject(resultStr);
		if (!obj.getInteger("code").equals(0)){	//同步失败
			return R.failed("从toutiao获取失败");
		}else{
			JSONArray data = obj.getJSONObject("data").getJSONArray("result");
			return R.ok(data, "获取成功");
		}*/
		return R.ok(data);
	}

	@Override
	public R industryList(String advertiserId) {

		InputStream is = this.getClass().getClassLoader().getResourceAsStream("industry.json");
		byte[] getData = new byte[0];
		try {
			getData = readInputStream(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String content = new String(getData);
		JSONArray data =  JSONObject.parseArray(content);
		return R.ok(data, "获取成功");

	}


	/*private static String readFileContent(String fileName) {
		File file = new File(fileName);
		BufferedReader reader = null;
		StringBuffer sbf = new StringBuffer();
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempStr;
			while ((tempStr = reader.readLine()) != null) {
				sbf.append(tempStr);
			}
			reader.close();
			return sbf.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return sbf.toString();
	}*/


	private static  byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}


}
